<template>
  <div class="yy-whp-month-reports">
    <!--列表-->
    <div class="yy-month-reports-list" v-show="type=='list'">
      <Card>
        <p slot="title">
          <Icon type="md-list" />
          月度结转报表
        </p>
        <Form ref="formInline" :model="searchForm"  inline>
          <FormItem prop="user">
            <Select class="select" v-model="searchForm.storageNum" @on-change="changeStorage(searchForm.storageNum)" placeholder="请选择仓库">
              <Option value="0">请选择</Option>
              <Option v-for="(dataSt,index) in dataStorage" :value="dataSt.storageNum" :key="index">{{dataSt.storageName}}</Option>
            </Select>
          </FormItem>
          <FormItem prop="user">
            <DatePicker type="date" placeholder="上次结存时间" style="width: 200px" v-model="searchForm.st" :options="startTimeOption" disabled></DatePicker>
          </FormItem>
          <FormItem prop="user">
            <DatePicker type="date" placeholder="本次结存时间" style="width: 200px" v-model="searchForm.et" :options="endTimeOption" @on-change="onEndTimeChange" ></DatePicker>
          </FormItem>
          <FormItem>
            <Button type="primary" @click="handleSearch()">载入数据</Button>
          </FormItem>
          <FormItem>
            <Button type="primary" @click="handleSearchTurn()">结存当月</Button>
          </FormItem>
        </Form>

        <Divider style="font-size: 20px;">月度汇总表</Divider>

        <Table :columns="columns" :data="data"></Table>
        <div style="margin: 10px;overflow: hidden">
          <div style="float: right;">
            <Page :total="page.total" :page-size="page.pageSize" :current="1" @on-change="changePage" show-total></Page>
          </div>
        </div>
      </Card>
    </div>
    <!--详情-->
    <div class="yy-month-reports-details" v-show="type=='details'">
       <Card>
        <p slot="title">
          <Icon type="md-paper"/>
          月度转结详情
          <p slot="extra">
            <Button type="primary" @click="goBack()">返回</Button>
          </p>
        </p>
        <Divider style="font-size: 20px;">月度汇总表 {{searchFormMonth.dayDate}}</Divider>
        <div class="count">合计： 入库：373975.14    出库：457274.80</div>
        <div class="sub-count">
          当页小计：初期库存：数量{{pageSubtotal.startNumTotal}} 金额{{pageSubtotal.startAmountTotal}} 
          | 本期收入：数量{{pageSubtotal.inNumTotal}} 金额{{pageSubtotal.inAmountTotal}} 
          | 本期发出：数量{{pageSubtotal.outNumTotal}} 金额{{pageSubtotal.outAmountTotal}} 
          | 期末结存：数量{{pageSubtotal.numTotal}} 金额{{pageSubtotal.amountTotal}}
        </div>
        <Table :columns="columnsA" :data="dataB" border></Table>
        <div style="margin: 10px;overflow: hidden">
          <div style="float: right;">
            <Page :total="page.total" :page-size="page.pageSize" :current="1" @on-change="changePageMonth" show-total></Page>
          </div>
        </div>
      </Card>
    </div>
  </div>
</template>

<script>
import API from "./api";
import ValidatorRule from "@/filters/validator-rule";
import { formatNetTime } from "@/libs/tools";
import i18n from "./locale";
import mixin from "@/mixin/date-mixin";
import wareHouseMixin from "../common/warehouse-mixin";

export default {
  name: "yy-whp-month-reports",
  mixins: [mixin, wareHouseMixin],
  data() {
    return {
      i18n: i18n,
      currentData: null,
      detailsModal: false,
      type: "list",
      endTimeOption: {
        disabledDate(date) {
          return date && date.valueOf() < Date.now() - 86400000;
        }
      },
      page: {
        total: 0,
        pageSize: 20
      },
      pageSubtotal: {
        startNumTotal: 0,
        startAmountTotal: 0,
        inNumTotal: 0,
        inAmountTotal: 0,
        outNumTotal: 0,
        outAmountTotal: 0,
        numTotal: 0,
        amountTotal: 0
      },
      pageSubtotalStart: {
        startNumTotal: 0,
        startAmountTotal: 0,
        inNumTotal: 0,
        inAmountTotal: 0,
        outNumTotal: 0,
        outAmountTotal: 0,
        numTotal: 0,
        amountTotal: 0
      },
      searchForm: {
        userID: "",
        userName: ""
      },
      searchFormMonth: {
        storageNum: "",
        hasNum: "",
        userID: "",
        userName: "",
        localNum: "",
        lastDayDate: "",
        dayDate: "",
        itemNum: "",
        itemName: ""
      },
      editFormInLine: {
        supplierNum: "",
        supplierName: "",
        contact: "",
        tel: "",
        remark: ""
      },
      editFormRuleInline: {
        supplierNum: ValidatorRule.require,
        supplierName: ValidatorRule.require,
        tel: ValidatorRule.tel
      },
      columns: [
        {
          title: "序号",
          type: "index"
        },
        {
          title: "仓库",
          key: "storageName"
        },
        {
          title: "时间",
          key: "dayDate"
        },
        {
          title: "操作",
          key: "action",
          width: 180,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.details(params.index);
                    }
                  }
                },
                "查看"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small"
                  },
                  on: {
                    click: () => {
                      this.delete(params.index, params.row.id);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ],
      data: [],
      columnsA: [
        {
          title: "物品编号",
          align: "center",
          key: "itemNum",
          width: 100
        },
        {
          title: "物品名称",
          align: "center",
          key: "itemName"
        },
        {
          title: "规格",
          align: "center",
          key: "size"
        },
        {
          title: "计量单位",
          align: "center",
          key: "unitName"
        },
        {
          title: "初期库存",
          align: "center",
          children: [
            {
              title: "数量",
              key: "startNum",
              align: "center"
            },
            {
              title: "金额",
              key: "startAmount",
              align: "center"
            }
          ]
        },
        {
          title: "本期收入",
          align: "center",
          children: [
            {
              title: "数量",
              key: "inNum",
              align: "center"
            },
            {
              title: "金额",
              key: "inAmount",
              align: "center"
            }
          ]
        },
        {
          title: "本期发出",
          align: "center",
          children: [
            {
              title: "数量",
              key: "outNum",
              align: "center"
            },
            {
              title: "金额",
              key: "outAmount",
              align: "center"
            }
          ]
        },
        {
          title: "期末结存",
          align: "center",
          children: [
            {
              title: "数量",
              key: "num",
              align: "center"
            },
            {
              title: "金额",
              key: "amount",
              align: "center"
            }
          ]
        }
      ],
      dataB: [],
      dataTatol: [] //算页面小计
    };
  },

  mounted() {
    this.userInfo = this.$store.state.user.userInfo;
    this.handleSearch();
  },

  computed: {},

  methods: {
    handleSearch() {
      let obj = {
        userID: "",
        userName: ""
      };
      obj.pageNum = 1;
      obj.pageSize = this.page.pageSize;
      this.searchForm = obj;
      this.getList(obj);
    },

    handleSearchTurn() {
      let obj = {
        lastDayDate: "",
        dayDate: "",
        userID: "",
        userName: "",
        storageNum: ""
      };
      API.checkMonth(obj)
        .then(res => {
          if (res.code == 200) {
            this.resetList();
            this.$Message.success("结算成功！");
            this.goBack();
          }
        })
        .catch(err => {
          this.$Message.error("结算异常！");
        });
    },

    getList(obj) {
      API.getList(obj)
        .then(res => {
          if (res.code == 200) {
            let data = res.data;
            this.page.total = data.total;
            this.page.pageSize = data.pageSize;
            this.data = data.list;
            this.searchForm.startTime = new Date(data.list[0].dayDate);
          }
        })
        .catch(err => {
          this.$Message.error("请求异常！");
        });
    },

    changePage(pageNum) {
      let obj = this.searchForm,
        maxPageNum = Math.ceil(this.page.total / this.page.pageSize);
      if (obj.pageNum > maxPageNum) {
        obj.pageNum = maxPageNum;
      } else {
        obj.pageNum = pageNum;
      }
      this.searchForm = obj;
      this.getList(obj);
    },

    goBack() {
      this.type = "list";
    },

    details(index) {
      this.type = "details";
      let obj = {
        storageNum: "",
        hasNum: "",
        userID: "",
        userName: "",
        localNum: "",
        lastDayDate: "",
        dayDate: "",
        itemNum: "",
        itemName: ""
      };
      obj.pageNum = 1;
      obj.pageSize = this.page.pageSize;
      this.searchFormMonth = obj;
      this.searchFormMonth.dayDate = this.data[index].dayDate;
      this.getDetails(obj);
    },
    getDetails(obj) {
      API.getDetails(obj)
        .then(res => {
          if (res.code == 200) {
            let datadet = res.data;
            this.dataTatol = res.data;
            this.dataB = datadet.list;
            this.thisPageSubtotal();
          }
        })
        .catch(err => {
          this.$Message.error("请求异常！");
        });
    },
    changePageMonth(pageNum) {
      let obj = this.searchFormMonth,
        maxPageNum = Math.ceil(this.page.total / this.page.pageSize);
      if (obj.pageNum > maxPageNum) {
        obj.pageNum = maxPageNum;
      } else {
        obj.pageNum = pageNum;
      }
      this.searchFormMonth = obj;
      this.getDetails(obj);
    },

    delete(index, id) {
      let tthis = this;
      this.$Modal.confirm({
        title: "提示：",
        content: "你确定删除这条记录",
        onOk: function() {
          let obj = {
            userID: tthis.userInfo.userId,
            userName: tthis.userInfo.userName,
            dayDate: new Date(),
            storageNum: ""
          };
          API.delete(obj)
            .then(res => {
              if (res.code == 200) {
                this.$Message.success({ content: "该记录已经删除成功！" });
                tthis.data.splice(index, 1);
                tthis.resetList();
              }
            })
            .catch(err => {
              console.log(err);
              this.$Message.error("请求异常！");
            });
        }
      });
    },

    resetList() {
      //求余为1，页码为最大页码，请求页需减1
      let maxPageNum = Math.ceil(this.page.total / this.page.pageSize);
      let remainderNum = this.page.total % this.page.pageSize;
      if (
        this.searchForm.pageNum == maxPageNum &&
        remainderNum == 1 &&
        this.searchForm.pageNum !== 1
      ) {
        this.searchForm.pageNum = this.searchForm.pageNum - 1;
      }
      let obj = this.searchForm;
      this.getList(obj);
    },

    thisPageSubtotal() {
      let obj = {
        startNumTotal: 0,
        startAmountTotal: 0,
        inNumTotal: 0,
        inAmountTotal: 0,
        outNumTotal: 0,
        outAmountTotal: 0,
        numTotal: 0,
        amountTotal: 0
      };
      for (let i in this.dataB) {
        obj.startNumTotal += this.dataB[i].startNum;
        obj.startAmountTotal += this.dataB[i].startAmount * 100;
        obj.inNumTotal += this.dataB[i].inNum;
        obj.inAmountTotal += this.dataB[i].inAmount * 100;
        obj.outNumTotal += this.dataB[i].outNum;
        obj.outAmountTotal += this.dataB[i].outAmount * 100;
        obj.numTotal += this.dataB[i].num;
        obj.amountTotal += this.dataB[i].amount * 100;
      }
      obj.startAmountTotal = obj.startAmountTotal / 100;
      obj.inAmountTotal = obj.inAmountTotal / 100;
      obj.outAmountTotal = obj.outAmountTotal / 100;
      obj.amountTotal = obj.amountTotal / 100;
      this.pageSubtotal = obj;
    }
  }
};
</script>
<style lang="less" >
@import "./yy-whp-month-reports.less";
</style>
